﻿package de.gameduell.framework.facebook {
	import de.gameduell.framework.facebook.reporting.FBBaseTracker;
	import de.gameduell.framework.debug.Debug;
	import de.gameduell.framework.util.Library;

	import flash.display.Sprite;
	import flash.events.EventDispatcher;

	public class FBBasePageManager extends EventDispatcher {

		protected var library:Library;
		protected var baseController:IFBBaseController;
		protected var pages:Array;
		protected var _currentPage:IPage;
		protected var timeline:Sprite;
		protected var coverUp:Sprite;
		protected var tracker:FBBaseTracker;
		protected var _layoutManager:FBBaseAppLayout;

		public function FBBasePageManager(aController:IFBBaseController){
			baseController = aController;
			library = Library.getInstance();
			pages = new Array();
			coverUp = library.createSprite("coverUp");
			tracker = FBBaseTracker.getInstance();
			_layoutManager = FBBaseAppLayout.getInstance();
		}
		
		public function getController():IFBBaseController {
			return baseController;
		}

		public function init(aTimeline:Sprite):void{
			timeline = aTimeline;
		}

		public function addPage(aPage:IPage):IPage{
			pages[aPage.id] = aPage;
			if(aPage.showInstant){
				show(aPage.id);
			}
			return aPage;
		}

		public function hide(pageId:String):void {
			if(pages[pageId] != null){
				IPage(pages[pageId]).hide();
			}
		}
		
		public function show(pageId:String):void {
			if(pages[pageId] != null){
				var aPage:IPage = IPage(pages[pageId]);
				if(_currentPage != null){
					if(_currentPage.isContent && IPage(pages[pageId]).isContent && !isSameContent(pageId)){
						_currentPage.hide();
					}
				}
				if(!isSameContent(pageId)){
					_currentPage = aPage.isContent ? aPage : _currentPage;
					timeline.addChild(aPage.sprite);
				}
				aPage.show();	
				if(aPage.isContent){
					tracker.appContext = pageId;
				}
			}
		}
		
		protected function isSameContent(aPageId:String):Boolean {
			if(_currentPage != null){
				return _currentPage.id == aPageId;
			}
			return false;
		}
		
		public function set covered(isCovered:Boolean):void {
			if(coverUp != null){
				if(isCovered){
					timeline.addChild(coverUp);
				}else{
					try{
						timeline.removeChild(coverUp);
					}catch(e:Error){
						Debug.trace("FBBasePageManager:: set covered: cover clip not available ....", Debug.WARNING);
					}
				}
			}
		}
		
		public function moveScreen(offset:int):void {
			Debug.trace("FBBaseManager::moveScreen: from: " + timeline.y + " to -> " + offset, Debug.DEBUG);
			timeline.y += offset;
			_layoutManager.currentYOffset += offset;
		}
		
		public function get currentPage():IPage {
			return _currentPage;
		}
	}
}
